package api

import (
	"gitee.com/alex_li/beacon-config/internal/etc"
	"github.com/kataras/iris/v12"
	"github.com/lishimeng/app-starter"
)

type LoginReq struct {
	Name     string `json:"name,omitempty"`
	Password string `json:"password,omitempty"`
}

func SignIn(ctx iris.Context) {

	var err error
	var req LoginReq
	var resp app.Response

	err = ctx.ReadJSON(&req)

	if err != nil {
		resp.Code = 500
		_ = ctx.JSON(resp)
		return
	}

	if req.Name == etc.Config.Admin.Name && req.Password == etc.Config.Admin.Password {
		resp.Code = 200
		s := genSession()
		resp.Message = s
		_ = ctx.JSON(resp)
	} else {
		resp.Code = 401
		_ = ctx.JSON(resp)
	}
}

func SignOut(ctx iris.Context) {

	var resp app.Response
	resp.Code = 200
	_ = ctx.JSON(resp)
}

func isLogin(ctx iris.Context) {
	s := ctx.GetHeader("s")
	if len(s) <= 0 {
		ctx.StatusCode(401)
		return
	}
	if !checkSession(s) {
		ctx.StatusCode(401)
		return
	}

	ctx.Next()
}
